<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible="visible"
      :modal-append-to-body="false"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-card class="box-card" shadow="never">
        <el-row>
          <el-upload
            class="upload_body"
            ref="bacthUpload"
            :action="actionUrl"
            accept=".xls, .xlsx"
            :limit="1"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeFileUpload"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
          </el-upload>
          <el-divider content-position="left">导入说明</el-divider>
          <div class="link-left">
            <li
              v-for="(content, index) in liContents"
              :key="index"
            >
              <span v-html="content"></span>
            </li>
          </div>
        </el-row>
      </el-card>
      <el-row slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          :loading="loading.submit"
          type="primary"
          @click="handleSubmit"
        >提交</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {},
  props: {
    visible: { // 弹框开关
      type: Boolean,
      required: true
    },
    dialogTitle: { // 弹框标题
      type: String,
      default: ''
    },
    contents: { // 导入说明下预渲染的li文本集合
      type: Array,
      default () {
        return [
          '线下整理好需导入的表格。',
          '表格格式：SKU编码、启用状态（1为启用、2为禁用）、适用客户类型（工程,工业,政府,商贸）。',
          '导入表格从第二行开始导入，第一行为表头不导入。',
          '当导入的商品SKU编码错误，则不进行导入，即导入不成功。',
          '主推导入，不支持导入主推区域，主推区域默认为全部。',
          '提交后页面关闭，系统后台更新数据，根据数据量大小更新时间不同。',
          '每次导入的限制为5W。'
        ]
      }
    },
    actionUrl: { // 导入接口
      type: String,
      default: ''
    },
    limitSize: { // 上传大小限制，默认10M
      type: Number,
      default: 10
    }
  },
  data () {
    return {
      dialogVisible: false,
      fileList: [], // 上传文件
      liContents: [], // 处理后的导入说明下预渲染的li文本集合
      importLoading: false, // 上传loading
      loading: {
        import: null,
        submit: false
      }
    };
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
    },
    contents: {
      immediate: true,
      handler (list) {
        this.liContents = list.map(item => {
          return this.getStrByReg(item);
        });
      }
    }
  },
  methods: {
    // 获取正则表达式处理后的字符串（同一行下中文括号内的文本内容标红）
    getStrByReg (content) {
      const reg = /(?<=（)[^）]+/g;
      if (!reg.test(content)) {
        return content;
      }
      const replaceText = content.match(reg);
      for (let i = 0; i < replaceText.length; i++) {
        let replaceStr = `（<span class="error_color">${replaceText[i]}</span>）`;
        content = content.replace(RegExp(`（${replaceText[i]}）`, 'g'), replaceStr);
      }
      return content;
    },
    // 更改loading状态
    changeLoadingByState (state = false) {
      if (state) {
        this.loading.import = this.$loading({ target: '.upload_body' });
      } else {
        this.loading.import.close();
      }
      this.loading.submit = state;
    },
    // 上传成功回调
    uploadSuccess (res, file, fileList) {
      this.changeLoadingByState();
      if (isResponseSuccessState(res.retStatus)) {
        this.$message.success('上传成功');
        this.closeDialog();
        this.clearState();
      } else {
        this.$message.error(res.retMessage)
      }
    },
    // 上传失败回调
    uploadError (res) {
      this.changeLoadingByState();
      this.$message.error(res.error || '提交失败');
    },
    // 上传前回调
    beforeFileUpload (file) {
      this.changeLoadingByState(true);
      const isLimitSize = file.size / 1024 / 1024 < this.limitSize;
      if (!isLimitSize) {
        this.$message.error(`上传文件大小不能超过${this.limitSize}MB!`);
      }
      return isLimitSize;
    },
    // 预览回调
    handlePreview (file) {
      console.log(file);
    },
    // 移除回调
    handleRemove (file, fileList) {
      console.log(file);
      console.log(fileList);
    },
    // 提交
    handleSubmit () {
      this.$refs.bacthUpload.submit();
    },
    // 关闭弹框
    handleClose () {
      this.closeDialog();
      this.clearState();
    },
    // 关闭弹框
    closeDialog () {
      this.$emit('update:visible', false);
    },
    // 清空上传状态
    clearState () {
      this.$refs.bacthUpload.clearFiles();
    }
  }
};
</script>
<style lang="less" scoped>
.line {
  height: 100%;
  width: 3px;
  background: olivedrab;
}
.link-left {
  font-size: 14px;
  color: #5c5b5b;
  height: 100%;
  .text-warning {
    color: red;
  }
}
</style>
